package com.java.service.impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import com.java.dao.AccountWalletMapper;
import com.java.model.*;
import darabonba.core.client.ClientOverrideConfiguration;

//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.util.concurrent.CompletableFuture;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.dao.MediaAccountMapper;
import com.java.service.MediaAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;

@Service
public class MediaAccountServiceImpl implements MediaAccountService {

    int i = 0;

    @Autowired
    private MediaAccountMapper mediaAccountMapper;

    @Autowired
    private MediaAccountService mediaAccountService;

    @Autowired
    private AccountWalletMapper accountWalletMapper;


    @Override
    public Result modify(MediaAccount mediaAccount) {
        return null;
    }

    @Override
    public Result remove(int[] ids) {
        return null;
    }

    @Override
    public Result list(MediaAccount mediaAccount) {
        PageHelper.startPage(mediaAccount.getPageNum(), mediaAccount.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<MediaAccount> list = mediaAccountMapper.list(mediaAccount);
        PageInfo<MediaAccount> pageInfo = new PageInfo<>(list);

        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Result advertisingLogin(MediaAccount mediaAccount, HttpServletRequest request) {
        MediaAccount mediaAccount1 = mediaAccountMapper.advertisingLogin(mediaAccount);
        if (mediaAccount1 != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", mediaAccount1);

            //查询媒体主有没有钱包账号 没有则添加钱包
            AccountWallet accountWallet1 = accountWalletMapper.mediaRecharge(mediaAccount1.getId());
            if (accountWallet1.getAvailableBalance() == null){
                AccountWallet accountWallet = new AccountWallet();
                accountWallet.setAccountId(mediaAccount1.getId());
                accountWalletMapper.code(accountWallet);
            }


//            // 在用户登录成功后查询当前用户拥有的权限并存储（存储在Session中）
//            List<Permission> userPermissionList = mediaAccountMapper.listByLoginId(Integer.valueOf(log.getId()));
//            session.setAttribute("userPermissionList", userPermissionList);
//
//            // 查询系统中管理员的所有权限并存储（存储在Session域中）
//            Permission permission = new Permission();
//            permission.setPageSize(999);
//            Result result = mediaAccountMapper.toList(permission);
//            session.setAttribute("permissionList", result.getData());
            return Result.success();
        }

        return Result.error("用户名或密码错误");
    }

    @Override
    public List<MediaAccount> saveList() {
        return mediaAccountMapper.saveList();
    }

    @Override
    public List<MediaAccount> toList() {
        return mediaAccountMapper.toList();
    }

    @Override
    public List<MediaAccount> listByLoginId(int login) {
        return mediaAccountMapper.listByLoginId(login);
    }

    @Override
    public List<MediaAccount> searchList(MediaAccount mediaAccount) {
        return mediaAccountMapper.searchList(mediaAccount);
    }

    @Override
    public Result modification(MediaAccount mediaAccount) {
        mediaAccount.getId();
        mediaAccountMapper.modification(mediaAccount);
        return Result.success();
    }

    /**
     * 同意
     * @param mediaAccount
     * @return
     */
    @Override
    public Result agree(MediaAccount mediaAccount) {
        mediaAccount.setStatus(3);
        mediaAccountMapper.agree(mediaAccount);
        return Result.success();
    }

    /**
     * 拒绝
     * @param mediaAccount
     * @return
     */
    @Override
    public Result refused(MediaAccount mediaAccount) {
        mediaAccount.setStatus(4);
        mediaAccountMapper.refused(mediaAccount);
        return Result.success();
    }

    @Override
    public Result priceId(int id) {
        MediaAccount mediaAccount = mediaAccountMapper.priceId(id);
        return Result.success(mediaAccount, null);
    }

    @Override
    public Result priceUpdate(Price price) {
        mediaAccountMapper.priceUpdate(price);
        return Result.success();
    }

    @Override
    public Result priceSave(Price price) {
        mediaAccountMapper.priceSave(price);
        return Result.success();
    }

    @Override
    public Result passwordSave(MediaAccount mediaAccount) {
        mediaAccountMapper.passwordSave(mediaAccount);
        return Result.success();
    }

    @Override
    public Result resource(MediaAccount mediaAccount) {
        PageHelper.startPage(mediaAccount.getPageNum(), mediaAccount.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<MediaAccount> resource = mediaAccountMapper.resource(mediaAccount);
        PageInfo<MediaAccount> pageInfo = new PageInfo<>(resource);

        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Result resourceList(MediaAccount mediaAccount) {
        PageHelper.startPage(mediaAccount.getPageNum(), mediaAccount.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<MediaAccount> resource = mediaAccountMapper.resourceList(mediaAccount);
        PageInfo<MediaAccount> pageInfo = new PageInfo<>(resource);

        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Result resourceList2(MediaAccount mediaAccount) {
        PageHelper.startPage(mediaAccount.getPageNum(), mediaAccount.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<MediaAccount> resource = mediaAccountMapper.resourceList2(mediaAccount);
        PageInfo<MediaAccount> pageInfo = new PageInfo<>(resource);
        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Result resourceList3(MediaAccount mediaAccount) {
        PageHelper.startPage(mediaAccount.getPageNum(), mediaAccount.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<MediaAccount> resource = mediaAccountMapper.resourceList3(mediaAccount);
        PageInfo<MediaAccount> pageInfo = new PageInfo<>(resource);
        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Result resourceList4(MediaAccount mediaAccount) {
        PageHelper.startPage(mediaAccount.getPageNum(), mediaAccount.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<MediaAccount> resource = mediaAccountMapper.resourceList4(mediaAccount);
        PageInfo<MediaAccount> pageInfo = new PageInfo<>(resource);
        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Result resourceList5(MediaAccount mediaAccount) {
        PageHelper.startPage(mediaAccount.getPageNum(), mediaAccount.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<MediaAccount> resource = mediaAccountMapper.resourceList5(mediaAccount);
        PageInfo<MediaAccount> pageInfo = new PageInfo<>(resource);
        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Result resourceRemove(int[] ids) {
        for (int id : ids) {
            mediaAccountMapper.resourceRemove(id);
        }
        return Result.success();
    }

    @Override
    public Result get(int id) {
        MediaAccount mediaAccount = mediaAccountMapper.get(id);
        return Result.success(mediaAccount, null);
    }

    /**
     * 短信验证
     * @param phoneNum
     * @return
     */
    @Override
    public Result message(String phoneNum) {
        Random random = new Random(); // 用于作为随机数的验证码
        i = random.nextInt(9999 - 1000 + 1) + 1000;
        System.out.println(i);

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5t8g5krDi9M2ewcM1pjr") // accessKeyId值
                .accessKeySecret("oT5qZ1wPbMigmIWmgDQvhqF55KNhzZ") //accessKeySecret值
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("阿里云短信测试")
                .templateCode("SMS_154950909")
                .phoneNumbers(phoneNum)
                .templateParam("{\"code\":\"" + i +"\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();

        return Result.success();
    }

//    /**
//     * 头像上传
//     * @param headImg
//     * @return
//     */
//    @Override
//    public Result upload(String headImg) {
//        return null;
//    }

    @Override
    @Transactional(readOnly = false)
    public Result save(MediaAccount mediaAccount) {
        if (mediaAccount.getPhoneCode().equals(i)) { // 判断验证码是否一致
//            Date date = new Date(); // 获取时间
//            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMdd");
//            mediaAccount.setUsername("WIVF" + dateFormat.format(date));
//            mediaAccount.setAccountName(""); // 自媒体名字
            mediaAccount.setHeadImg("/img/QQ图片20200508145514.jpg"); // 头像图片
            mediaAccount.setPlatformId(1); // 所属平台
            mediaAccount.setFansAmount("0"); // 粉丝数量
            mediaAccount.setSubsAmount("0"); // 订阅数量
            mediaAccount.setAccountPv("0"); // 访问量
            mediaAccount.setOwner(1); // 账号归属
            mediaAccount.setStatus(1); // 状态
            mediaAccountMapper.save(mediaAccount);


            // 注册成功后查询
            Price price = new Price();
            price.setAccountId(mediaAccount.getId()); // 未测试功能是否可用
            mediaAccountMapper.priceSave(price);
//            List<MediaAccount> mediaAccounts = mediaAccountMapper.toList();
//            MediaAccount mediaAccount2 = mediaAccountMapper.priceId(mediaAccount1.getId());
//            if (mediaAccount2.getPrice().getAccountId() == null && mediaAccount2 != null) {
//                Price price = new Price();
//                price.setAccountId(mediaAccount1.getId());
//                mediaAccountMapper.priceSave(price);
//            }

            return Result.error("注册成功");
        } else {
            return Result.error("验证码不一致");
        }
    }
}
